import styled from 'styled-components';
import React, { CSSProperties, FC, useCallback, useEffect, useState } from 'react';
import cn from '@/utils/classnames'
import type {
    EditorState,
} from 'lexical'
import {
    $getRoot,
    TextNode,
} from 'lexical'

import { LexicalComposer } from '@lexical/react/LexicalComposer'
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'
import { ContentEditable } from '@lexical/react/LexicalContentEditable'
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary'
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'
import Placeholder from './plugins/placeholder'

export interface PromptEditorProps {
    style?: CSSProperties;
    className?: string
    placeholder?: string
    placeholderClassName?: string
    editable?: boolean
    onChange?: (text: string) => void
    compact?: boolean
}

export const PromptEditor: FC<PromptEditorProps> = ({ style, placeholder, compact, className, placeholderClassName, onChange, editable }) => {

    const initialConfig = {
        namespace: 'prompt-editor',
        nodes: [
        ],
        onError: (error: Error) => {
            throw error
        },
    }

    const handleEditorChange = (editorState: EditorState) => {
        const text = editorState.read(() => {
            return $getRoot().getChildren().map(p => p.getTextContent()).join('\n')
        })
        if (onChange)
            onChange(text)
    }

    return (
        <LexicalComposer initialConfig={{ ...initialConfig, editable }}>
            <Container className='relative min-h-5' style={style}>
                <RichTextPlugin
                    contentEditable={<ContentEditable className={`${className} outline-none ${compact ? 'leading-5 text-[13px]' : 'leading-6 text-sm'} text-gray-700`} style={style || {}} />}
                    placeholder={<Placeholder value={placeholder} className={cn('truncate', placeholderClassName)} compact={compact} />}
                    ErrorBoundary={LexicalErrorBoundary}
                />
                <OnChangePlugin onChange={handleEditorChange} />
                <HistoryPlugin />
            </Container>
        </LexicalComposer>
    );
}

const Container = styled.div`
    background-color: #FFF;
`;

